<template>
  <div id="organization" class="views">
    <div class="pageMain">
      <el-col style="height: 100%">
        <div class="oper-nav">
          <div class="search-from">
            <el-input placeholder="请输入" v-model="filterText"></el-input>
            <el-button type="primary" :loading="sectiontreeLoading" @click="serch">搜索</el-button>
          </div>
          <!-- <div class="search-btns">
            <el-button type="primary" @click="operation({ level: 0 }, 'add')" round>添加公司</el-button>
          </div> -->
        </div>
        <div class="tableContent">
          <div class="header">
            <span class="title">公司名称</span>
            <span class="title">员工数</span>
            <span class="title">部门负责人</span>
          </div>
          <div class="treeMain">
            <el-tree ref="tree" :filter-node-method="filterNode" :data="treedepartmentData" nodeKey="id" :props="departmentdefaultProps" @node-expand="nodeExpand" @node-collapse="nodeCollapse" :default-expanded-keys="expanded" :render-content="sectionrenderContent" :indent="0" v-loading="sectiontreeLoading"></el-tree>
          </div>
        </div>
      </el-col>
    </div>
    <!-- 删除弹框 -->
    <delPopup @delPostConfirm="delTreeNodePost" :delPopup="delPopup" />
    <!-- 新增修改部门弹框 -->
    <el-dialog :title="depTreeChangePopup.title" :visible.sync="depTreeChangePopup.isShow" width="380px" @closed="handleClose">
      <el-form :model="industryParams" :rules="rules" ref="depForm" label-width="100px" style="padding: 40px 0">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model.trim="industryParams.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <!-- v-if="jurisdictionControl.J_SetPrincipal" -->
        <el-form-item label="负责人" prop="personId">
          <el-select v-model="industryParams.personId" placeholder="请选择负责人" filterable>
            <el-option v-for="item in userListNew" :key="item.userid" :label="item.realName || item.userName" :value="item.userid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="depTreeChangePopup.isShow = false" round>取 消</el-button>
        <el-button size="medium" type="primary" @click="changeDep" round :loading="isConfirmLoading">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mixinsMethod } from "@/util/util";
import { mapState } from "vuex";
import delPopup from "@/components/delPopup";
import dep from "@/assets/images/department.png";
import com from "@/assets/images/company.png";
export default {
  name: "organization",
  components: {
    delPopup,
  },
  data() {
    return {
      filterText: "",
      jurisdictionControl: {
        // 权限
        J_AddDep: false, // 新增部门
        J_EditDep: false, // 修改部门
        J_DelDep: false, // 删除部门
        // J_AddFirm: false, // 新增企业
        // J_EditFirm: false, // 修改企业
        // J_DelFirm: false, // 删除企业
        J_AddUser: false, // 新增职员
        J_EditUser: false, // 修改职员
        J_DelUser: false, // 删除职员
        // J_SetPrincipal: false, //设置部门负责人
      },
      defaultProps: {
        children: "subList",
        label: "subName",
      },
      departmentdefaultProps: {
        children: "childrens",
        label: "name",
      },
      treeLoading: false,
      sectiontreeLoading: false,
      treedepartmentData: [],
      treeData: [],
      paramsData: {},
      userList: [],
      delPopup: {
        // 删除
        title: "",
        isShow: false,
        describe: "",
      },
      industryParams: {
        // 部门添加修改 params
        departmentName: "", // 部门名称
        companyid: "", // 企业id
        level: "", // 级次
        parentid: 0, // 父级id
        personId: "", //  负责人id
        subid: "", // 子公司id
      },
      depTreeChangePopup: {
        // 部门添加修改弹框
        title: "",
        isShow: false,
        type: "",
      },
      delDepParams: {}, //删除部门
      delStaffParams: {}, // 删除职员
      isConfirmLoading: false, // 确认的loading
      userCount: 0, // 临时存储员工数
      expanded: [],
      rules: {
        departmentName: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
        personId: [{ required: false, message: "请选择负责人", trigger: "chage" }],
      },
      exportUserDialog: false, //控制导入员工dialog的显示
      searchParams: {
        deptKeyWord: "",
        keyWord: "",
      },
      userListNew: [],
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.common.userInfo,
      moduleId: (state) => state.common.moduleId,
    }),
  },
  methods: {
    serch() {
      this.$refs.tree.filter(this.filterText);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    DeleteAccount(subid) {
      // 删除账套的弹框和参数
      this.delDepParams = {
        subid,
      };
      this.delPopup = {
        title: "删除账套",
        isShow: true,
        describe: "此操作会将当前公司下所有用户的账号关闭（管理员除外）,不可登录,请谨慎操作",
        istype: 2,
      };
    },

    sectionrenderContent(h, { data }) {
      // 自定义部门|职员 tree节点
      return (
        <span class="sectiontreenode" on-mouseenter={() => this.setis_show(data)} on-mouseleave={() => this.setis_show(data)}>
          <span class="sectionItem newItem" style={data.level != 1 ? "padding-left:" + data.level * 5 + "px" : ""}>
            <img src={data.type == 1 ? com : dep} alt="" />
            <span>{data.name}</span>
          </span>
          <span class="sectionItem">{data.num}</span>
          <span class="sectionItem textcenter">{data.personName}</span>
          <div class="operation sectionItem">
            <i class="iconfont" title="新增子部门" on-click={() => this.sectiontreeoperation(data, "add")}>
              &#xe632;{" "}
            </i>
            <i class="iconfont" title={data.type == 1 ? "编辑公司" : "编辑部门"} on-click={() => this.sectiontreeoperation(data, "edit")}>
              &#xe631;{" "}
            </i>
            <i class="iconfont" title={data.type == 1 ? "删除公司" : "删除部门"} on-click={() => this.sectiontreeoperation(data, "del")}>
              &#xe612;{" "}
            </i>
          </div>
        </span>
      );
    },
    setTreeData(data) {
      // 公司树初始化
      data.map((item) => {
        item.is_show = false;
        if (item.subList && item.subList.length != 0) {
          item.icons = "1";
          this.setTreeData(item.subList);
        } else {
          item.icons = "2";
        }
      });
    },

    async getTreeData(type) {
      // 获取树
      const {
        data: { data: res },
      } = await this.$api.systemManagement.GetStructureDepartmentTree();
      const { data } = await this.$api.publicApi.GetSubCompanyView();
      const treeToArray = (data) => data.reduce((p, c) => p.concat(c, treeToArray(c.childrenList)), []);
      const depArr = treeToArray(res);
      let treeData = data.data.childrens;
      let users = [];
      // 添加level
      const addLevel = (data, level = 1) => {
        users.push(...data.filter((i) => i.type === 3));
        data = data.filter((i) => i.type !== 3);
        data.map((i) => {
          i.level = level;
          const item = depArr.find((f) => f.departmentid === i.id) || {};
          i.Id = item?.id;
          i.personName = item.personName;
          i.personId = item.personId;
          if (i.childrens && i.childrens.length) {
            i.childrens = addLevel(i.childrens, level + 1);
          }
        });
        return data;
      };
      const addNum = (data) => {
        data.map((i) => {
          if (i.childrens && i.childrens.length) {
            addNum(i.childrens);
          }

          if (i.type == 1) {
            i.num = users.filter((c) => c.companyId === i.id).length;
          }
          if (i.type == 2) {
            i.num = users.filter((c) => c.parentId === i.id).length;
            if (i.num == 0) {
              i.childrens.map((m) => {
                i.num += m.num;
              });
            }
          }
        });
      };
      let d = addLevel(treeData);
      addNum(d);
      this.treedepartmentData = d;
      this.getUserList1();
    },
    getUserList1() {
      // 获取负责人列表
      this.$api.systemManagement.GetUserList(this.paramsData).then((res) => {
        let resData = res.data.data;
        this.userList = resData;
      });
    },

    treeoperation(data, type) {
      // 公司tree 操作
      event.stopPropagation();
      if (!data.isSelect) {
        this.$message({ message: "暂无权限", type: "warning" });
        return;
      }
      switch (type) {
        case "add":
          if (!this.jurisdictionControl.J_AddFirm) {
            this.$message({ message: "暂无权限", type: "warning" });
            return;
          }
          this.$store.commit("companyInfo/balance", true);
          this.$store.commit("companyInfo/checkCurtain", false);
          this.$store.commit("companyInfo/EditAccount", false);
          if (data.level == 0) {
            this.$router.push({ name: "editCompany", query: { jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          } else {
            this.$store.commit("companyInfo/setPrint", data.subid); // 保存客户id
            this.$router.push({ name: "editCompany", query: { isAdd: true, subid: data.subid, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          }
          break;
        case "check":
          this.$router.push({ name: "checkCompany", query: { isCheck: true, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          this.$store.commit("companyInfo/setPrint", data.subid); // 保存客户id
          this.$store.commit("companyInfo/checkCurtain", true); // 查看状态为true
          this.$store.commit("companyInfo/balance", false); // 新建状态为 false
          this.$store.commit("companyInfo/EditAccount", false); // 编辑状态为 false
          break;
        case "edit":
          if (!this.jurisdictionControl.J_EditFirm) {
            this.$message({ message: "暂无权限", type: "warning" });
            return;
          }
          this.$router.push({ name: "editCompany", query: { isEdit: true, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          this.$store.commit("companyInfo/setPrint", data.subid); // 保存客户id
          this.$store.commit("companyInfo/checkCurtain", true); // 查看状态为true
          this.$store.commit("companyInfo/balance", false); // 新建状态为 false
          this.$store.commit("companyInfo/EditAccount", true); // 编辑状态为 false
          break;
        default:
          break;
      }
    },

    getuserCount(data, userCount, istype) {
      // 获取员工数
      if (userCount) {
        this.userCount = Number(userCount);
      }
      if (istype) {
        data.map((item) => {
          this.userCount += Number(item.userCount);
          if (item.childrenList && item.childrenList.length != 0) {
            this.getuserCount(item.childrenList, false, true);
          }
        });
        return;
      }
      if (data.childrenList && data.childrenList.length != 0) {
        data.childrenList.map((item) => {
          this.userCount += Number(item.userCount);
          if (item.childrenList && item.childrenList.length != 0) {
            this.getuserCount(item.childrenList, false, true);
          }
        });
        return;
      }
    },

    getmergeListFun(resList, level) {
      // 部门职员数据初始化
      resList.map((item) => {
        item.isbranch = true;
        item.is_show = false;
        item.level = level ? level + 1 : 1;
        this.getuserCount(item, item.userCount);
        item.userCount = this.userCount;
        this.userCount = 0;
        if (item.childrenList && item.childrenList.length != 0) {
          this.getmergeListFun(item.childrenList, item.level);
        }
        if (item.userList && item.userList.length != 0) {
          item.userList.map((i) => {
            i.isbranch = false;
            i.is_show = false;
            i.level = item.level + 1;
          });
        }
        if (item.userList) {
          item.mergeList = item.userList;
        } else {
          item.mergeList = [];
        }
        if (item.childrenList) {
          item.mergeList = [...item.childrenList, ...item.mergeList];
        }
      });
      return resList;
    },

    setis_show(data) {
      data.is_show = !data.is_show;
    },

    nodeExpand(node) {
      this.expanded.push(node.id);
    },
    nodeCollapse(node) {
      let index = this.expanded.indexOf(node.id);
      this.expanded.splice(index, 1);
    },

    sectiontreeoperation(data, type) {
      // 部门 | 职员tree 操作
      console.log(data, this.userList);
      this.userListNew = this.userList.filter((i) => i.subid === data[data.type == 1 ? "id" : "companyId"]);
      event.stopPropagation();
      switch (type) {
        case "add":
          this.cleardepTreeForm();
          this.industryParams = {
            departmentName: "", // 部门名称
            companyid: this.userInfo.CompanyId, // 企业id
            level: data.level, // 级次
            parentid: data.type == 1 ? "" : data.id, // 父级id
            rootid: "", //
            personId: "", //  负责人id
            subid: data.type == 1 ? data.id : data.companyId, // 子公司id
          };
          this.depTreeChangePopup = {
            title: "部门添加",
            isShow: true,
            type: "add",
          };
          break;
        case "edit":
          if (data.type == 1) {
            this.operation(data, "edit");
          }
          if (data.type == 2) {
            if (data.type == 2) {
              let personId;
              if (data.personId && data.personId != "00000000-0000-0000-0000-000000000000") {
                personId = data.personId;
              }
              this.industryParams = {
                id: data.Id,
                departmentName: data.name, // name
                departmentid: data.id, //  部门id
                personId, //  负责人id
                subid: data.companyId, // 子公司id
              };
              this.depTreeChangePopup = {
                title: "部门修改",
                isShow: true,
                type: "edit",
              };
            }
          }

          break;
        case "del":
          if (data.type == 1) {
            this.DeleteAccount(data.id);
          }
          if (data.type == 2) {
            this.delDepParams = {
              id: data.Id,
              departmentid: data.id, //  部门id
              parentid: data.parentId, // 父级id
              subid: data.companyId, // 子公司id
            };
            this.delPopup = {
              title: "删除部门",
              isShow: true,
              describe: "确定删除该部门吗？",
              istype: 1,
            };
          }
          break;
        default:
          break;
      }
    },

    operation(data, type) {
      // 操作
      switch (type) {
        case "add":
          this.$store.commit("companyInfo/balance", true);
          this.$store.commit("companyInfo/checkCurtain", false);
          this.$store.commit("companyInfo/EditAccount", false);
          if (data.level == 0) {
            this.$router.push({ name: "addCompany", query: { type: 1, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          } else {
            // this.$store.commit('companyInfo/setPrint', data.subid) // 保存客户id
            // this.$router.push({ name: 'addCompany',query:{isAdd:true, subid:data.subid, jurisdictionControl: JSON.stringify(this.jurisdictionControl)}})
          }
          break;
        case "check":
          this.$router.push({ name: "checkCompany", query: { isCheck: true, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          this.$store.commit("companyInfo/setPrint", data.subid); // 保存客户id
          this.$store.commit("companyInfo/checkCurtain", true); // 查看状态为true
          this.$store.commit("companyInfo/balance", false); // 新建状态为 false
          this.$store.commit("companyInfo/EditAccount", false); // 编辑状态为 false
          break;
        case "edit":
          console.log(data);
          this.$router.push({ name: "editCompany", query: { type: 1, isEdit: true, jurisdictionControl: JSON.stringify(this.jurisdictionControl) } });
          this.$store.commit("companyInfo/setPrint", data.id); // 保存客户id
          this.$store.commit("companyInfo/checkCurtain", true); // 查看状态为true
          this.$store.commit("companyInfo/balance", false); // 新建状态为 false
          this.$store.commit("companyInfo/EditAccount", false); // 编辑状态为 false
          break;
        default:
          break;
      }
    },

    changeDep() {
      // 新增修改部门
      this.$refs["depForm"].validate((valid) => {
        if (valid) {
          this.isConfirmLoading = true;
          switch (this.depTreeChangePopup.type) {
            case "add":
              let params = {
                ...this.industryParams,
                islets: true,
              };
              this.$api.systemManagement
                .DepartmentEdit(params, 1)
                .then((res) => {
                  if (res.data.status === 200) {
                    this.$notify({
                      title: "成功",
                      message: "新增部门成功",
                      type: "success",
                      duration: 1500,
                    });
                    this.depTreeChangePopup.isShow = false;
                    this.getTreeData();
                  }
                  setTimeout(() => {
                    // 延迟开启确认
                    this.isConfirmLoading = false;
                  }, 500);
                })
                .catch(() => {
                  this.isConfirmLoading = false;
                });
              break;
            case "edit":
              let params1 = {
                ...this.industryParams,
              };
              this.$api.systemManagement
                .DepartmentEdit(params1, 2)
                .then((res) => {
                  if (res.data.status === 200) {
                    this.$notify({
                      title: "成功",
                      message: "修改部门成功",
                      type: "success",
                      duration: 1500,
                    });
                    this.depTreeChangePopup.isShow = false;
                    this.getTreeData();
                  }
                  setTimeout(() => {
                    // 延迟开启确认
                    this.isConfirmLoading = false;
                  }, 500);
                })
                .catch(() => {
                  this.isConfirmLoading = false;
                });
              break;
            default:
              break;
          }
        } else {
          return false;
        }
      });
    },

    delTreeNodePost() {
      // tree 删除部门或者职员的请求
      if (this.delPopup.istype == "1") {
        //删除部门
        let params = {
          ...this.delDepParams,
        };
        this.$api.systemManagement.DeleteDepartment(params).then((res) => {
          if (res.data.status === 200) {
            this.$message({ message: "删除成功", type: "success" });
            this.getTreeData();
          }
          this.delPopup.isShow = false;
        });
      } else {
        //删除公司
        this.$api.companyInfo.DeleteRecycle(this.delDepParams).then((res) => {
          if (res.data.status === 200) {
            this.$message({ message: "删除成功", type: "success" });
            this.getTreeData();
          }
          this.delPopup.isShow = false;
        });
      }
    },

    cleardepTreeForm() {
      // 清空表单验证
      this.$nextTick(() => {
        if (this.$refs["depForm"]) {
          this.$refs["depForm"].resetFields();
        }
      });
    },

    handleClose() {
      // 清空绑定的数据
      this.clearObjVal(this.industryParams);
    },
  },
  mounted() {
    this.getTreeData();
  },
  activated() {},
  mixins: [mixinsMethod],
};
</script>
<style lang="less">
#organization {
  .pageMain {
    height: 100% !important;

    .el-col-5 {
      width: 330px !important;
    }

    .el-col-19 {
      width: calc(100% - 350px) !important;
    }

    height: 100%;
    margin-top: 0;

    .oper-nav {
      width: 100%;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .search-from {
        display: flex;
        align-items: center;

        .el-input {
          margin-right: 20px;
        }

        .input-name {
          width: 266px;
        }

        .input-dep {
          width: 200px;
        }

        .input-name {
          width: 300px;
        }
      }
    }

    .tableContent {
      height: calc(100% - 52px);
      // height: 100%;
      border: 1px solid #e7ebf5;
      padding: 0;

      .header {
        width: 100%;
        height: 36px;
        background-color: #f5f8fd;
        line-height: 36px;
        font-size: 12px;
        color: #333;

        .title {
          display: inline-block;
          width: 27%;
          height: 100%;
          color: #333;
          padding-left: 10px;
          float: left;
        }

        .title:nth-child(3) {
          text-align: center;
        }

        .title:nth-child(4) {
          width: 19%;
          position: relative;
        }

        .addbtn {
          float: right;
          margin: 3px 4px 0 0;
          // margin: 8px 8px 0 0;
        }
      }

      .sectiontreenode {
        display: block;
        width: 100%;
        font-size: 12px;
        height: 40px;
        line-height: 40px;

        .sectionItem {
          display: inline-block;
          width: 27%;
        }

        .newItem {
          img {
            // width: 20px;
            float: left;
            height: 20px;
            margin-top: 8px;
            margin-right: 5px;
          }

          div {
          }
        }

        .textcenter {
          text-align: center;
        }

        .operation {
          width: 19%;
          text-align: center;

          i {
            font-size: 15px;
            margin-left: 10px;
            color: #39a4ed;
          }
        }

        .head {
          display: inline-block;
          width: 25px;
          height: 25px;
          border-radius: 50%;
          background-color: #6bd0f4;
          line-height: 25px;
          text-align: center;
          margin-right: 5px;
          color: #fff;
          font-size: 12px;
        }
      }

      .el-tree-node__content {
        height: auto;
        border-bottom: 1px solid #e7ebf5;

        &:hover {
          color: #333 !important;
        }
      }

      .treeMain {
        width: 100%;
        height: calc(100% - 35px);
        overflow: auto;
      }
    }

    .treeContent {
      border: 1px solid #e7ebf5;
      height: 100%;
      font-size: 14px;
      width: 100%;

      .treeHead {
        background: #f5f8fd;
        height: 36px;
        line-height: 36px;
        padding: 0 20px;
        width: 100%;

        .treeHeadRight {
          color: #6595ef;
          text-align: right;

          .AddText {
            cursor: pointer;
          }

          span {
            &:last-child {
              margin-left: 2px;
            }
          }
        }
      }

      .treeMain {
        width: 100%;
        padding: 8px 0 0 8px;
        height: calc(100% - 60px);
        overflow: auto;
        box-sizing: border-box;

        .el-tree-node {
          &:hover .iconfont {
            color: #606266;
          }
        }

        .custom-tree-node {
          display: flex;
          align-items: baseline;
          width: 88%;

          .icon1 {
            color: #f29b5c !important;
            font-size: 15px;
          }

          .icon2 {
            color: #92b5f7 !important;
            font-size: 14px;
          }

          .pull_right {
            float: right;

            .iconfont {
              font-size: 15px;
              margin-left: 10px;

              &:hover {
                color: #5c8ffc;
              }
            }
          }

          .name_text {
            margin-left: 5px;
            display: inline-block;
            width: 100%;
          }
        }

        .is-current {
          color: #39a4ed;
          background-color: #f5f7fa;
        }
      }
    }
  }
}
</style>
